import type { FormInstance } from 'element-plus'
import type { loopConfigureColorEnum } from '~/store/assetManagement/facilityManagement/typings'
import type {
  LoopInformationPropsType,
  LoopInformationFormValuesType,
  LoopInformationStateType
} from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { uniqueId, values } from 'lodash'
import {
  ElRow,
  ElCol,
  ElSpace,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElColorPicker,
  ElLink,
  // ElIcon,
  ElButton,
  ElTooltip,
  ElMessage
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import AliIcon from '~/components/AliIocn'
import LoopInfoMap from '../map/LoopInfoMap'
import useVuexGetters from '~/hooks/useVuexGetters'
import { GUTTER, SPAN_STYLE_TWO_THIRD, SPAN_STYLE_ONE_THIRD } from '~/utils/const'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'LoopInformation',
  props: ['detail'],
  setup(props: LoopInformationPropsType, { expose }) {
    const store = useStore()
    const loopInfoMapRef = ref()
    const ruleFormRef = ref<FormInstance>()
    const state = reactive<LoopInformationStateType>({
      // 只做排序用
      loopList: [],
      // 用于过滤回路下拉框可选项  里面存的是已选中的下拉框值
      hasLoopNumList: [],
      // 用于给回路传初始值的方法
      initLoopInfo: undefined,
      deleteLoopIds: []
    })
    const formValues = reactive<{ [prop: string]: LoopInformationFormValuesType }>({})
    const loopMonitoringBoxState = useVuexGetters('loopMonitoringBox', ['loopConfigureColorList'])

    // 切换randomId
    const handleToggleActiveRandomId = (
      randomId: string,
      activeLoopType: LoopInformationStateType['activeLoopType'],
      strokeColor?: string
    ) => {
      const flag = state.activeRandomId === randomId
      // 当是绘制时 点击关闭时时获取到路径信息并赋值到输入框中
      // 绘制取消高亮  绘制切换灯杆  切换不同回路绘制 都要保存
      if (activeLoopType === 'draw') {
        if (state.activeRandomId && state.activeLoopDraw) {
          const { loopPhase, lampPostIds } = loopInfoMapRef.value.changeCurrentPattern()
          formValues[state.activeRandomId!].phase = loopPhase
          formValues[state.activeRandomId!].lampPostIds = lampPostIds
        }

        // 如果flag存在则draw按钮是true且poles自动变为false
        if (!flag) {
          state.activeLoopDraw = true
          state.activeLoopPoles = false
          loopInfoMapRef.value.changePolesVisible(false)
        } else {
          state.activeLoopDraw = !state.activeLoopDraw
        }
      }
      // 判断当前回路是否存在关联灯杆号
      if (activeLoopType === 'poles') {
        if (!formValues[randomId].lampPostIds?.length) {
          ElMessage.warning('该回路暂无关联灯杆')
          return
        }

        // 如果flag存在则draw按钮是poles且draw自动变为false
        if (!flag) {
          state.activeLoopPoles = true
          state.activeLoopDraw = false
          loopInfoMapRef.value.changeShowPoles(formValues[randomId].lampPostIds)
        } else {
          state.activeLoopPoles = !state.activeLoopPoles
          if (state.activeLoopPoles) {
            loopInfoMapRef.value.changeShowPoles(formValues[randomId].lampPostIds)
          } else {
            loopInfoMapRef.value.changePolesVisible(false)
          }
        }
      }

      // 切换状态
      if (flag && !state.activeLoopDraw && !state.activeLoopPoles) {
        state.activeRandomId = undefined
        state.activeStrokeColor = undefined
      } else {
        state.activeRandomId = randomId
        state.activeStrokeColor = strokeColor
      }
    }

    // 切换回路回调
    const handleChangeLoopName = (value: string, randomId: string) => {
      // 如果之前有颜色则先把先前颜色下的画的图形和关联灯杆保存
      if (state.activeStrokeColor) {
        const { loopPhase, lampPostIds } = loopInfoMapRef.value.changeCurrentPattern()
        formValues[state.activeRandomId!].phase = loopPhase
        formValues[state.activeRandomId!].lampPostIds = lampPostIds
      }

      const prevColor = loopMonitoringBoxState.loopConfigureColorList.value?.find(
        (item: loopConfigureColorEnum) => item.loopNum === value
      )?.color
      loopInfoMapRef.value?.changeLoopPatternColor?.(formValues[randomId].color, prevColor)
      formValues[randomId].color = prevColor
      state.hasLoopNumList =
        values(formValues)
          .map((item: LoopInformationFormValuesType) => item?.loopName)
          .filter(Boolean) || []

      if (state.activeLoopPoles) {
        loopInfoMapRef.value.changePolesVisible(false)
      }
      state.activeRandomId = undefined
      state.activeStrokeColor = undefined
      state.activeLoopDraw = false
      state.activeLoopPoles = false
      state.hasLoopNumList.push(value)
    }

    // 新增回路
    const handleAddLoop = () => {
      const { detail } = props
      if (state.loopList?.length >= loopMonitoringBoxState.loopConfigureColorList.value?.length)
        return
      const addLoopItem: loopConfigureColorEnum =
        loopMonitoringBoxState.loopConfigureColorList.value.find(
          (item: loopConfigureColorEnum) => !state.hasLoopNumList?.includes(item.loopNum!)
        )
      state.hasLoopNumList.push(addLoopItem.loopNum!)
      // 生成一个随机编码用于记录
      const randomId = uniqueId('loop')
      state.loopList.push(randomId)
      formValues[randomId] = {
        distributionId: detail.id,
        distributionName: detail.name,
        color: addLoopItem.color,
        loopName: addLoopItem.loopNum
      }
    }

    // 删除回路
    const handleDeleteLoop = async (randomId: string) => {
      state.activeRandomId = randomId
      // 只是本地新增的时候
      if (!formValues[randomId]?.id) {
        loopInfoMapRef.value.mapToolbar.toDeletePattern(formValues[randomId].color)
        state.loopList = state.loopList.filter((item) => item !== randomId)
        state.hasLoopNumList = state.hasLoopNumList.filter(
          (item) => item !== formValues[randomId].loopName
        )
        delete formValues[randomId]
        state.activeRandomId = undefined
        state.activeStrokeColor = undefined
        state.activeLoopDraw = false
        state.activeLoopPoles = false
        return
      }
      // 在修改的时候先查询是否可以删除  如果是则才可以删除
      const res = await store.dispatch(
        'powerDistributionFacilities/GetWhetherDeletePowerDistributionFacilitiesLoop',
        { distributionLoopId: formValues[randomId]?.id }
      )
      if (res?.success) {
        loopInfoMapRef.value.mapToolbar.toDeletePattern(formValues[randomId].color)
        state.loopList = state.loopList.filter((item) => item !== randomId)
        state.hasLoopNumList = state.hasLoopNumList.filter(
          (item) => item !== formValues[randomId].loopName
        )
        state.deleteLoopIds.push(formValues[randomId].id!)
        delete formValues[randomId]
        state.activeRandomId = undefined
        state.activeStrokeColor = undefined
        state.activeLoopDraw = false
        state.activeLoopPoles = false
      }
    }

    // 当控制所有路灯显示按钮打开时 及时在也关闭父组建的灯杆显示按钮关闭
    const handleChangeActiveLightPole = (visible: boolean) => {
      if (!visible || !state.activeLoopPoles) return
      state.activeRandomId = undefined
      state.activeStrokeColor = undefined
      state.activeLoopDraw = false
      state.activeLoopPoles = false
    }

    // 校验当前是否位于画图状态 是则关闭画图状态
    const handleVerifyActiveLoopType = () => {
      if (state.activeLoopDraw && state.activeRandomId) {
        const { loopPhase, lampPostIds } = loopInfoMapRef.value.changeCurrentPattern()
        formValues[state.activeRandomId!].phase = loopPhase
        formValues[state.activeRandomId!].lampPostIds = lampPostIds
        // 切换状态
        state.activeRandomId = undefined
        state.activeStrokeColor = undefined
        state.activeLoopDraw = false
        state.activeLoopPoles = false
      }
    }

    onMounted(async () => {
      // 根据配电设施id 查询关联的回路信息
      const res = await store.dispatch('loopMonitoringBox/GetPowerDistributionFacilityCircuit', {
        distributionId: props.detail.id
      })
      const initLoopInfo: LoopInformationStateType['initLoopInfo'] = {}
      Object.assign(
        formValues,
        (res?.data || [])?.reduce(
          (
            obj: Record<string, LoopInformationFormValuesType>,
            item: LoopInformationFormValuesType
          ) => {
            if (item.id) {
              obj[item.id] = {
                ...item,
                lampPostIds: (item.lampPostIds as unknown as string)?.split?.(','),
                color: loopMonitoringBoxState.loopConfigureColorList.value?.find(
                  (findItem: loopConfigureColorEnum) => findItem.loopNum === item.loopName
                )?.color
              }
              if (obj[item.id].color && (item.phase || item.lampPostIds)) {
                let loopInfo = initLoopInfo[obj[item.id].color as string]
                if (initLoopInfo) {
                  loopInfo = initLoopInfo[obj[item.id].color as string] = {}
                }
                loopInfo.lampPostIds = obj[item.id].lampPostIds as string[]
                loopInfo.phase =
                  obj[item.id].phase && JSON.parse(obj[item.id].phase as unknown as string)
                obj[item.id].phase = loopInfo.phase
              } else {
                obj[item.id].phase = undefined
              }
              state.loopList.push(item.id)
              state.hasLoopNumList.push(item.loopName!)
            }
            return obj
          },
          {}
        )
      )
      state.initLoopInfo = initLoopInfo
      // 如果接口请求返回没有list则去默认新增一个
      // if (!state.loopList?.length) {
      //   handleAddLoop()
      // }
    })

    expose({
      ruleFormRef,
      formValues,
      deleteLoopIds: state.deleteLoopIds,
      verifyActiveLoopType: handleVerifyActiveLoopType
    })

    return () => (
      <ElRow gutter={GUTTER} class={styles['info-content-height-full-box']}>
        <ElCol {...SPAN_STYLE_ONE_THIRD}>
          <ElForm inline class={styles['loop-info-form']} ref={ruleFormRef} model={formValues}>
            <ElRow gutter={GUTTER}>
              <ElCol>
                <ElFormItem>
                  <ElButton
                    type="primary"
                    icon={Plus}
                    disabled={
                      state.loopList?.length >=
                      loopMonitoringBoxState.loopConfigureColorList.value?.length
                    }
                    onClick={handleAddLoop}
                  >
                    新增
                  </ElButton>
                </ElFormItem>
              </ElCol>
              {/* {state.loopList?.length <
                loopMonitoringBoxState.loopConfigureColorList.value?.length && (
                <ElCol>
                  <ElFormItem>
                    <ElButton type="primary" icon={Plus} onClick={handleAddLoop}>
                      新增
                    </ElButton>
                  </ElFormItem>
                </ElCol>
              )} */}
              {state.loopList.map((randomId) => (
                <ElCol>
                  <ElFormItem prop="id">
                    <ElInput type="hidden" v-model={formValues[randomId].id} />
                  </ElFormItem>
                  {/* <ElFormItem prop="phase">
                    <ElInput type="hidden" v-model={formValues[randomId].phase} />
                  </ElFormItem> */}
                  <ElFormItem prop="lampPostIds">
                    <ElInput type="hidden" v-model={formValues[randomId].lampPostIds} />
                  </ElFormItem>
                  <ElSpace>
                    <ElFormItem
                      label="回路"
                      prop={`${randomId}.loopName`}
                      rules={[
                        {
                          required: true,
                          message: '请选择回路信息'
                        }
                      ]}
                    >
                      <ElSelect
                        v-model={formValues[randomId].loopName}
                        onChange={(value: string) => handleChangeLoopName(value, randomId)}
                      >
                        {loopMonitoringBoxState.loopConfigureColorList.value?.map(
                          (item: loopConfigureColorEnum) => (
                            <ElOption
                              key={item?.loopNum}
                              label={item?.loopNum}
                              value={item?.loopNum!}
                              disabled={state.hasLoopNumList?.includes(item?.loopNum!)}
                            />
                          )
                        ) || []}
                      </ElSelect>
                    </ElFormItem>
                    <ElFormItem prop="color" class={styles['loop-color-picker']}>
                      <ElColorPicker v-model={formValues[randomId].color} disabled />
                    </ElFormItem>
                    <ElFormItem>
                      <ElTooltip effect="light" content="地图上画图">
                        <ElLink
                          underline={false}
                          type={
                            state.activeRandomId === randomId && state.activeLoopDraw
                              ? 'primary'
                              : 'default'
                          }
                          onClick={() =>
                            handleToggleActiveRandomId(
                              randomId,
                              'draw',
                              formValues[randomId].color!
                            )
                          }
                        >
                          <AliIcon type="icon-huatu" />
                        </ElLink>
                      </ElTooltip>
                    </ElFormItem>
                    <ElFormItem>
                      <ElTooltip effect="light" content="显示/隐藏灯杆">
                        <ElLink
                          underline={false}
                          type={
                            state.activeRandomId === randomId && state.activeLoopPoles
                              ? 'primary'
                              : 'default'
                          }
                          onClick={() =>
                            handleToggleActiveRandomId(
                              randomId,
                              'poles',
                              formValues[randomId].color!
                            )
                          }
                        >
                          <AliIcon type="icon-denggan" />
                        </ElLink>
                      </ElTooltip>
                    </ElFormItem>
                    <ElFormItem>
                      <ElTooltip effect="light" content="删除后请点击保存">
                        <ElLink underline={false} onClick={() => handleDeleteLoop(randomId)}>
                          <AliIcon type="icon-shanchu" />
                        </ElLink>
                      </ElTooltip>
                    </ElFormItem>
                  </ElSpace>
                </ElCol>
              ))}
            </ElRow>
          </ElForm>
        </ElCol>
        <ElCol {...SPAN_STYLE_TWO_THIRD}>
          {state.initLoopInfo && (
            <LoopInfoMap
              ref={loopInfoMapRef}
              id={styles['loop-info-map']}
              detail={props.detail}
              toolbarVisible={state.activeLoopDraw}
              initLoopInfo={state.initLoopInfo}
              strokeColor={state.activeStrokeColor}
              onChangeLightPoleVisible={handleChangeActiveLightPole}
            />
          )}
        </ElCol>
      </ElRow>
    )
  }
})
